<?php

namespace App\Console\Commands\Image;

use App\Models\Digital;
use App\Services\Http;
use App\Services\LogTrait;
use Illuminate\Console\Command;

class Qsbk extends Command
{

    use LogTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'image:qs_bk {type}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '糗事百科图片抓取';

    /**
     * 抓取选项
     *
     * @var array
     */
    protected $options = [
        'hot'   => [
            'uri'   => 'imgrank',
            'page'  => 13
        ],
        'solid' => [
            'uri'   => 'pic',
            'page'  => 35
        ]
    ];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @throws \Exception
     * @return mixed
     */
    public function handle()
    {
        try{
            $this->logName = $this->signature;

            $type = $this->argument('type');
            if( !in_array($type, array_keys($this->options)) ) {
                $this->logWrite('请输入正确的类型: host | solid');
                return;
            }

            $options = $this->options[$type];

            $http = Http::getInstance([
                'base_uri' => 'https://www.qiushibaike.com'
            ]);

            for ( $i = 1; $i <= $options['page']; $i++ ){
                $this->logWrite('image:qs_bk start parse '.$i.' page....');
                $url = '/'.$options['uri'].'/page/'.$i.'/';
                $response = $http->request('get', $url, [
                    'headers' => [
                        'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
                        'Host' => 'www.qiushibaike.com',
                        'Sec-Fetch-Mode' => 'navigate',
                        'Sec-Fetch-Site' => 'none',
                        'Sec-Fetch-User' => '?1',
                        'Upgrade-Insecure-Requests' => 1,
                        'Cookie'  => '_xsrf=2|99ed3066|4892ce8ac97294848336dd4a08c88bd0|1567761365; Hm_lvt_2670efbdd59c7e3ed3749b458cafaa37=1567761367; _ga=GA1.2.186435061.1567761368; _gid=GA1.2.906270897.1567761368; __cur_art_index=5800; _qqq_uuid_="2|1:0|10:1567908474|10:_qqq_uuid_|56:YTA4MjQ1MjNhZTM0NzdmOWNkYWIzOGY2YmIwMWVkZDYxNWEzNGMxZQ==|4cc815f33390d0636fea1e3d4d2585043fcb16ec4e96cb12030072b3d33e90b3"; Hm_lpvt_2670efbdd59c7e3ed3749b458cafaa37=1567909123; _gat=1',
                        'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
                    ]
                ]);
                $contents = $response->getBody()->getContents();
                $data = $this->parse($contents);
                $this->dataToDb($data);
                $this->logWrite('image:qs_bk start parse '.$i.' page get data total:'.count($data).'');
            }
        }catch (\Exception $e){
            $this->logWrite($e->getMessage());
            $this->logWrite($e->getTraceAsString());
        }
    }

    public function parse($contents)
    {
        preg_match_all('/<div class="content">[\s\S]*?<span>([\s\S]*?)<\/span>[\s\S]*?<\/div>/', $contents, $match);
        $title = $match[1];

        preg_match_all('/<img src="(\/\/pic.qiushibaike.com\/system\/pictures\/.*?\/.*?\/medium\/((?!imageView).)*?)" .*>/', $contents, $match);
        $url = $match[1];

        preg_match_all('/<span class="stats-vote"><i class="number">(.*)<\/i> 好笑<\/span>/', $contents, $match);
        $like = $match[1];

        $data = [];
        array_walk($title, function ($val, $key) use (&$data, $url, $like) {
            $data[$key] = [
                'title'         => $val,
                'first_image'   => 'https:' . $url[$key],
                'url'           => 'https:' . $url[$key],
                'like'          => $like[$key],
                'source'        => 1,
                'type'          => 1
            ];
        });

        return $data;
    }

    public function dataToDb($data)
    {
        foreach ( $data as $row ){
            Digital::query()->updateOrCreate([
                'url' => $row['url']
            ],$row);
        }
    }

}
